<?php   
namespace app\mobile\controller;
use think\Controller;
use app\mall\model\Channel;
use think\Request;
use app\user\model\User as usermodel;
use think\Session;
use think\Config;
class Weixin extends Controller
{


    
    protected $db_user;
    
    private function hdb($db_name = 'app_user') {

        return $this->db_user = Db::connect(Config::get("database")["$db_name"]);
    }



    public function index()
    {

        if (!isset($_GET['echostr'])) {
            $this->responseMsg();
        }else{
            $this->valid();
        }

    }

    //验证签名
    public function valid()
    {
        $echoStr = $_GET["echostr"];
        $signature = $_GET["signature"];
        $timestamp = $_GET["timestamp"];
        $nonce = $_GET["nonce"];
        $token = 'weixin';
        $tmpArr = array($token, $timestamp, $nonce);
        sort($tmpArr, SORT_STRING);
        $tmpStr = implode($tmpArr);
        $tmpStr = sha1($tmpStr);
        if($tmpStr == $signature){
            echo $echoStr;
            exit;
        }
    }



   //响应消息
    public function responseMsg()
    {
        //$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        $postStr = file_get_contents("php://input");
        if (!empty($postStr)){
           // $this->logger("R \r\n".$postStr);
            $postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
            $RX_TYPE = trim($postObj->MsgType);
            $fromUsername = $postObj->FromUserName;
            //$toUsername = $postObj->ToUserName;
            $EventKey = $postObj->EventKey;
            if (($postObj->MsgType == "event") && ($postObj->Event == "subscribe" || $postObj->Event == "unsubscribe")){
                //过滤关注和取消关注事件
            }else{
                
            }


            //关注用户人的个人信息
            $user_openid_info = $this->piopen($fromUsername);

            if(preg_match("/^\w+\d$/",$EventKey)||preg_match("/^[0-9]\d$/",$EventKey))
            {
                //邀请人ID
                $from_uid  = substr(strrchr($EventKey, "_"), 1);

                $url =  'http://5g.xxxxxxx.com/user/user/user_openid_uid?&oid='.$user_openid_info.'&uid='.$from_uid;

                $this->mp_curl_get($url);
            }else{
                
                $url =  'http://5g.xxxxxxx.com/user/user/user_openid_uid?&oid='.$user_openid_info.'&uid=';

                $this->mp_curl_get($url);

            }


            //消息类型分离
            switch ($RX_TYPE)
            {
                case "event":
                    $result = $this->receiveEvent($postObj);
                     // file_put_contents('./event'.time().'.txt',$result);
                    break;
                case "text":
                   // if (strstr($postObj->Content, "第三方")){
                   //      $result = $this->relayPart3("http://www.fangbei.org/test.php".'?'.$_SERVER['QUERY_STRING'], $postStr);
                   //  }else{
                        $result = $this->receiveText($postObj);
                    // }
                    break;
                case "image":
                    $result = $this->receiveImage($postObj);
                    break;
                // case "location":
                //     $result = $this->receiveLocation($postObj);
                //     break;
                // case "voice":
                //     $result = $this->receiveVoice($postObj);
                //     break;
                // case "video":
                //     $result = $this->receiveVideo($postObj);
                //     break;
                // case "link":
                //     $result = $this->receiveLink($postObj);
                //     break;
                default:
                    $result = "unknown msg type: ".$RX_TYPE;
                    break;
            }
           // $this->logger("T \r\n".$result);
            echo $result;
        }else {
            echo "";
            exit;
        }
    }

    //接收事件消息
    private function receiveEvent($object)
    {
        $content = "";
        switch ($object->Event)
        {
            case "subscribe":
                $content = '您好!'."\n".'欢迎您关注';
               //$content .= (!empty($object->EventKey))?("\n来自二维码场景 ".str_replace("qrscene_","",$object->EventKey)):"";
                break;
            // case "unsubscribe":
            //     $content = "取消关注";
            //     break;
            case "CLICK": //自定义公众号的按钮事件
                switch ($object->EventKey)
                {
                    // case "COMPANY":
                    //     $content = array();
                    //     $content[] = array("Title"=>"商城", "Description"=>"", "PicUrl"=>"http://w.xxxxxx.com/assets/doubleshop/img/imges/banner01.png", "Url" =>"http://mp.weixin.qq.com/s?__biz=MzAxMDU3OTkxMw==&mid=2650134606&idx=1&sn=2c68eee49c513bec451224ad71bd355f&chksm=834f42e8b438cbfe2ba648b5cfc086a11b313645916b25e7fc1412915e1359a84cefd1eaa9dc#rd");
                    //     break;
                    case "QLUC":
                    
                        $openid = $object->FromUserName;//获取用户OPENID 
                        $url_uid = 'http://5g.xxxxxxxx.com/user/user/user_info_uid?&oid='.$openid; //用户OPENID换取数据库ID
                        $uid = $this->mp_curl_get($url_uid);
                        $uid = json_decode($uid,true);
                        if(!empty($uid))
                        {
                           
                            //获取素材库MID
                            $imageArray = $this->qrCode($uid['uid']);
                            $MediaId = array("MediaId"=>$imageArray);
                            //微信读取MID
                            echo $this->imagesmid($object,$MediaId);
                        }else{
                            echo  '亲~，系统繁忙请稍后再试！';
                        }   
                    break;
                    default:
                        $content = "点击菜单：".$object->EventKey;
                        break;
                }
                break;

            case "VIEW":
                $content = "跳转链接 ".$object->EventKey;
                break;
            case "SCAN":
                //$content = "扫描场景 ".$object->EventKey;
                $content = '您好!'."\n".'欢迎您关注717安全食品商城，您只要在“717安全食品商城”消费一次(不限金额)，即终身拥有“717安全食品商城”的“我的店铺”。'."\n"."\n".'分享我的店铺，成就您百万年薪的梦想。'."\n"."\n".'<a href="http://5g.xxxxxxxxxx.com/mobile/">717安全食品商城</a>';
                break;
            case "LOCATION":
                $content = "上传位置：纬度 ".$object->Latitude.";经度 ".$object->Longitude;
                break;
            case "scancode_waitmsg":
                if ($object->ScanCodeInfo->ScanType == "qrcode"){
                    $content = "扫码带提示：类型 二维码 结果：".$object->ScanCodeInfo->ScanResult;
                }else if ($object->ScanCodeInfo->ScanType == "barcode"){
                    $codeinfo = explode(",",strval($object->ScanCodeInfo->ScanResult));
                    $codeValue = $codeinfo[1];
                    $content = "扫码带提示：类型 条形码 结果：".$codeValue;
                }else{
                    $content = "扫码带提示：类型 ".$object->ScanCodeInfo->ScanType." 结果：".$object->ScanCodeInfo->ScanResult;
                }
                break;
            case "scancode_push":
                $content = "扫码推事件";
                break;
            case "pic_sysphoto":
                $content = "系统拍照";
                break;
            case "pic_weixin":
                $content = "相册发图：数量 ".$object->SendPicsInfo->Count;
                break;
            case "pic_photo_or_album":
                $content = "拍照或者相册：数量 ".$object->SendPicsInfo->Count;
                break;
            case "location_select":
                $content = "发送位置：标签 ".$object->SendLocationInfo->Label;
                break;
            default:
                $content = "receive a new event: ".$object->Event;
                break;
        }

        if(is_array($content)){
            if (isset($content[0]['PicUrl'])){
                $result = $this->transmitNews($object, $content);
            }else if (isset($content['MusicUrl'])){
                $result = $this->transmitMusic($object, $content);
            }
        }else{
            $result = $this->transmitText($object, $content);
        }
        return $result;
    }

    //接收文本消息
    private function receiveText($object)
    {
        $keyword = trim($object->Content);
        //多客服人工回复模式
        if (strstr($keyword, "请问在吗") || strstr($keyword, "在线客服")){
            $result = $this->transmitService($object);
            return $result;
        }

        //自动回复模式
        if (strstr($keyword, "商城")){
            $content = '请点击进入'."\n".'<a href="javascript:void(0);">商城</a>';
        }else if (strstr($keyword, "09d9d9ds0v")){
            $content = "中国：".$this->bytes_to_emoji(0x1F1E8).$this->bytes_to_emoji(0x1F1F3)."\n仙人掌：".$this->bytes_to_emoji(0x1F335);
        }else if (strstr($keyword, "0d0f0d0s0s01")){
            $content = array();
            $content[] = array("Title"=>"单图文标题",  "Description"=>"单图文内容", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
        }else if (strstr($keyword, "0d0f0d0s0saa0") || strstr($keyword, "90c0cf9d0s0w")){
            $content = array();
            $content[] = array("Title"=>"多图文1标题", "Description"=>"", "PicUrl"=>"http://discuz.comli.com/weixin/weather/icon/cartoon.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
            $content[] = array("Title"=>"多图文2标题", "Description"=>"", "PicUrl"=>"http://d.hiphotos.bdimg.com/wisegame/pic/item/f3529822720e0cf3ac9f1ada0846f21fbe09aaa3.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
            $content[] = array("Title"=>"多图文3标题", "Description"=>"", "PicUrl"=>"http://g.hiphotos.bdimg.com/wisegame/pic/item/18cb0a46f21fbe090d338acc6a600c338644adfd.jpg", "Url" =>"http://m.cnblogs.com/?u=txw1958");
        // }else if (strstr($keyword, "音乐")){
        //     $content = array();
        //     $content = array("Title"=>"最炫民族风", "Description"=>"歌手：凤凰传奇", "MusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3", "HQMusicUrl"=>"http://121.199.4.61/music/zxmzf.mp3"); 
        }else{

            $content = array();
            $content[] = array("Title"=>"717安全食品商城", "Description"=>"", "PicUrl"=>"http://w.xxxxxxxxxx.com/assets/doubleshop/img/imges/banner01.png", "Url" =>"http://mp.weixin.qq.com/s?__biz=MzAxMDU3OTkxMw==&mid=2650134606&idx=1&sn=2c68eee49c513bec451224ad71bd355f&chksm=834f42e8b438cbfe2ba648b5cfc086a11b313645916b25e7fc1412915e1359a84cefd1eaa9dc#rd");
            //$content = date("Y-m-d H:i:s",time())."\nOpenID：".$object->FromUserName."\n技术支持 工作室";
        }

        if(is_array($content)){
            if (isset($content[0])){
                $result = $this->transmitNews($object, $content);
            }else if (isset($content['MusicUrl'])){
                $result = $this->transmitMusic($object, $content);
            }
        }else{
            $result = $this->transmitText($object, $content);
        }
        return $result;
    }

    //接收图片消息
    private function receiveImage($object)
    {
        $content = array("MediaId"=>$object->MediaId);
        $result = $this->transmitImage($object, $content);
        return $result;
    }
    //接收位置消息
    private function receiveLocation($object)
    {
        $content = "你发送的是位置，经度为：".$object->Location_Y."；纬度为：".$object->Location_X."；缩放级别为：".$object->Scale."；位置为：".$object->Label;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    //接收语音消息
    private function receiveVoice($object)
    {
        if (isset($object->Recognition) && !empty($object->Recognition)){
            $content = "你刚才说的是：".$object->Recognition;
            $result = $this->transmitText($object, $content);
        }else{
            $content = array("MediaId"=>$object->MediaId);
            $result = $this->transmitVoice($object, $content);
        }
        return $result;
    }

    //接收视频消息
    private function receiveVideo($object)
    {
        $content = array("MediaId"=>$object->MediaId, "ThumbMediaId"=>$object->ThumbMediaId, "Title"=>"", "Description"=>"");
        $result = $this->transmitVideo($object, $content);
        return $result;
    }

    //接收链接消息
    private function receiveLink($object)
    {
        $content = "你发送的是链接，标题为：".$object->Title."；内容为：".$object->Description."；链接地址为：".$object->Url;
        $result = $this->transmitText($object, $content);
        return $result;
    }

    //回复文本消息
    private function transmitText($object, $content)
    {
        if (!isset($content) || empty($content)){
            return "";
        }

        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[text]]></MsgType>
    <Content><![CDATA[%s]]></Content>
</xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), $content);

        return $result;
    }

    //回复图文消息
    private function transmitNews($object, $newsArray)
    {
        if(!is_array($newsArray)){
            return "";
        }
        $itemTpl = "        <item>
            <Title><![CDATA[%s]]></Title>
            <Description><![CDATA[%s]]></Description>
            <PicUrl><![CDATA[%s]]></PicUrl>
            <Url><![CDATA[%s]]></Url>
        </item>
";
        $item_str = "";
        foreach ($newsArray as $item){
            $item_str .= sprintf($itemTpl, $item['Title'], $item['Description'], $item['PicUrl'], $item['Url']);
        }
        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[news]]></MsgType>
    <ArticleCount>%s</ArticleCount>
    <Articles>
$item_str    </Articles>
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time(), count($newsArray));
        return $result;
    }

    //回复音乐消息
    private function transmitMusic($object, $musicArray)
    {
        if(!is_array($musicArray)){
            return "";
        }
        $itemTpl = "<Music>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
        <MusicUrl><![CDATA[%s]]></MusicUrl>
        <HQMusicUrl><![CDATA[%s]]></HQMusicUrl>
    </Music>";

        $item_str = sprintf($itemTpl, $musicArray['Title'], $musicArray['Description'], $musicArray['MusicUrl'], $musicArray['HQMusicUrl']);

        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[music]]></MsgType>
    $item_str
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复图片消息
    private function transmitImage($object, $imageArray)
    {
        $itemTpl = "<Image>
        <MediaId><![CDATA[%s]]></MediaId>
    </Image>";

        $item_str = sprintf($itemTpl, $imageArray['MediaId']);

        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[image]]></MsgType>
    $item_str
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复语音消息
    private function transmitVoice($object, $voiceArray)
    {
        $itemTpl = "<Voice>
        <MediaId><![CDATA[%s]]></MediaId>
    </Voice>";

        $item_str = sprintf($itemTpl, $voiceArray['MediaId']);
        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[voice]]></MsgType>
    $item_str
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复视频消息
    private function transmitVideo($object, $videoArray)
    {
        $itemTpl = "<Video>
        <MediaId><![CDATA[%s]]></MediaId>
        <ThumbMediaId><![CDATA[%s]]></ThumbMediaId>
        <Title><![CDATA[%s]]></Title>
        <Description><![CDATA[%s]]></Description>
    </Video>";

        $item_str = sprintf($itemTpl, $videoArray['MediaId'], $videoArray['ThumbMediaId'], $videoArray['Title'], $videoArray['Description']);

        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[video]]></MsgType>
    $item_str
</xml>";

        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    //回复多客服消息
    private function transmitService($object)
    {
        $xmlTpl = "<xml>
    <ToUserName><![CDATA[%s]]></ToUserName>
    <FromUserName><![CDATA[%s]]></FromUserName>
    <CreateTime>%s</CreateTime>
    <MsgType><![CDATA[transfer_customer_service]]></MsgType>
</xml>";
        $result = sprintf($xmlTpl, $object->FromUserName, $object->ToUserName, time());
        return $result;
    }

    // //返回二维码图片
    public  function imagesmid($object,$content)
    {
       
    $xmlTpl = "<xml>
        <ToUserName><![CDATA[%s]]></ToUserName>
        <FromUserName><![CDATA[%s]]></FromUserName>
        <CreateTime>%s</CreateTime>
        <MsgType><![CDATA[image]]></MsgType>
        <Image>
        <MediaId><![CDATA[%s]]></MediaId>
        </Image>
        </xml>";
        $result =  sprintf($xmlTpl,$object->FromUserName, $object->ToUserName, time(),$content['MediaId']);
        return $result;
    }






    //回复第三方接口消息
    private function relayPart3($url, $rawData)
    {
        $headers = array("Content-Type: text/xml; charset=utf-8");
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $rawData);
        $output = curl_exec($ch);
        curl_close($ch);
        return $output;
    }

    //字节转Emoji表情
    function bytes_to_emoji($cp)
    {
        if ($cp > 0x10000){       # 4 bytes
            return chr(0xF0 | (($cp & 0x1C0000) >> 18)).chr(0x80 | (($cp & 0x3F000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else if ($cp > 0x800){   # 3 bytes
            return chr(0xE0 | (($cp & 0xF000) >> 12)).chr(0x80 | (($cp & 0xFC0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else if ($cp > 0x80){    # 2 bytes
            return chr(0xC0 | (($cp & 0x7C0) >> 6)).chr(0x80 | ($cp & 0x3F));
        }else{                    # 1 byte
            return chr($cp);
        }
    }


    //openid获取用户基本信息

    public function piopen($openid)
    {   

        $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=".$this->atoken()."&openid=".$openid."&lang=zh_CN";
        //$tokenarr=json_decode($this->mp_curl_get($url),true);
        $tokenarr= $this->mp_curl_get($url);
        return $tokenarr;
    }


    public function mp_custommenu_curl($url,$method='POST',$data)
    {
        $ch = curl_init();   //1.初始化
        curl_setopt($ch, CURLOPT_URL, $url); //2.请求地址
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);//3.请求方式
        //4.参数如下
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);//tps
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        if($method=="POST"){//5.post方式的时候添加数据
            curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
        }
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $tmpInfo = curl_exec($ch);//6.执行
        curl_close($ch);//8.关闭
        return $tmpInfo;
    }

    // token生成
    // public function accesstoken()
    // {
    //     $APPID='wx11c0be18bae0b48f';
    //     $SECRET = 'b11abf5fe28a06724ab3f8d62';
    //     $tokenurl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$APPID."&secret=".$SECRET;
    //     $tokenjson = $this->mp_curl_get($tokenurl);
    //     $tokenarr=json_decode($tokenjson,true);
    //     $token=$tokenarr['access_token'];
    //     return  $token;
    // }

    // public function accesstoken()
    // {
    //     $ctime = filectime('/data/www/api.xxxxxxxxxx.com/imagsQRcode/token.txt');
    //     if(file_exists($ctime) and (time() - $ctime) >= 7000) 
    //     {
    //      return $token = file_get_contents('/data/www/api.xxxxxxxxxx.com/imagsQRcode/token.txt');
    //     } 
    //     $APPID='wx11c0be18bae0b48f';
    //     $SECRET = 'b11abf5fe28a06724ab3f5';
    //     $tokenurl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=".$APPID."&secret=".$SECRET;
    //     $tokenjson = $this->mp_curl_get($tokenurl);
    //     $tokenarr=json_decode($tokenjson,true);
    //     $token=$tokenarr['access_token'];
    //     file_put_contents('/data/www/api.xxxxxxxxxx.com/imagsQRcode/token.txt', $token);
    //     return  $token;

    // }


    public function mp_curl_get($url)
    {
            $ch = curl_init();
            //设置选项，包括URL
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_TIMEOUT, 15);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);    // https请求 不验证证书和hosts
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            //执行并获取HTML文档内容
            $output = curl_exec($ch);
            //释放curl句柄
            curl_close($ch);
            //打印获得的数据
            return $output;
    }


    // //日志记录
    // private function logger($log_content)
    // {
    //     if(isset($_SERVER['HTTP_APPNAME'])){   //SAE
    //         sae_set_display_errors(false);
    //         sae_debug($log_content);
    //         sae_set_display_errors(true);
    //     }else if($_SERVER['REMOTE_ADDR'] != "127.0.0.1"){ //LOCAL
    //         $max_size = 1000000;
    //         $log_filename = "log.xml";
    //         if(file_exists($log_filename) and (abs(filesize($log_filename)) > $max_size)){unlink($log_filename);}
    //         file_put_contents($log_filename, date('Y-m-d H:i:s')." ".$log_content."\r\n", FILE_APPEND);
    //     }
    // }





/********************/

    //生成二维码
    public function qrCode($uid)
    {
        $url='https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token='.$this->atoken();
                    // $rest =rand(0,1000);
                    // error_log($url,3,'url'.$rest.".txt");
        $data=[
              "expire_seconds"=> 604800,
              "action_name"=> "QR_SCENE",
                  "action_info"=>[
                                  "scene"=>[
                                  "scene_id"=> $uid,
                                  ]
                  ]
        ];
        $res=Curl::callWebServer($url,json_encode($data), 'POST', 1 , 0);
        $ticket=$res['ticket'];
        //换取二维码图片
        $jpg=$this->rq_curl_get("https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".urlencode($ticket));
        //保存二维码路径
        $cq_path = '/data/www/api.xxxxxxxxxx.com/imagsQRcode/717'.time().'.jpg';
        file_put_contents($cq_path,$jpg);
       //   $this->rq_curl_get('./imagsQRcode/225.jpg',$jpg);
        //获取合成二维码路径
        $lb_qc  = $this->stimgas($cq_path);
        //$filename = "./st/xxxxxxxxxx".time().".jpg";
        $queryUrl = 'http://file.api.weixin.qq.com/cgi-bin/media/upload?access_token='.$this->atoken().'&type=image';
        $data = array();
        //上传素材库
        $data['media'] = Curl::addFile($lb_qc);
        $medias = Curl::callWebServer($queryUrl,$data, 'POST', 1 , 0);
        $mediast = json_encode($medias);
        $obj = json_decode($mediast);
        $mid= $obj->{'media_id'}; 
        unlink($cq_path);//删除QC
        unlink($lb_qc);//删除合成QC
        //返回素材库MID
        return $mid;
    }

    //token生成
    public function atoken()
    {
        $ctime = filectime('/data/www/api.xxxxxxxxxx.com/token.txt');
        if(file_exists($ctime) and (time() - $ctime) >= 7000) 
        {
         return $token = file_get_contents('/data/www/api.xxxxxxxxxx.com/token.txt');
        } 
        $tokenurl="https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx11c0be18bae0&secret=b11abf5fe28a06724ab3f8d6270a";
        $tokenjson = $this->rq_curl_get($tokenurl);
        $tokenarr=json_decode($tokenjson,true);
        $token=$tokenarr['access_token'];
        file_put_contents('/data/www/api.xxxxxxxxxx.com/token.txt', $token);
        return  $token;

    }


    public function rq_curl_get($url)
    {
            $ch = curl_init();
            //设置选项，包括URL
            curl_setopt($ch, CURLOPT_URL, $url);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($ch, CURLOPT_HEADER, 0);
            curl_setopt($ch, CURLOPT_TIMEOUT, 15);
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);    // https请求 不验证证书和hosts
            curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
            //执行并获取HTML文档内容
            $output = curl_exec($ch);
            //释放curl句柄
            curl_close($ch);
            //打印获得的数据
            return $output;
    }







    public function stimgas($cq_path){
    //底图
    $pathBasemap = "/data/www/api.xxxxxxxxxx.com/imagsQRcode/xxxxxxxxxx.jpg";
    //二维码图
    $pathQc = $cq_path;
    //将底图和二维码图片分别取到两个画布中
    $imageBasemap = imagecreatefromjpeg($pathBasemap);
    $imageQc = imagecreatefromjpeg($pathQc);
    //创建一个和底图一样大小的真彩色画布（ps：只有这样才能保证后面copy装备图片的时候不会失真）
    $imageCompose = imageCreatetruecolor(imagesx($imageBasemap),imagesy($imageBasemap));
    //为真彩色画布创建白色背景，再设置为透明
    $color = imagecolorallocate($imageCompose, 255, 255, 255);
    imagefill($imageCompose, 0, 0, $color);
    imageColorTransparent($imageCompose, $color);
    //首先将底图画布采样copy到真彩色画布中，不会失真
    imagecopyresampled($imageCompose,$imageBasemap,0,0,0,0,imagesx($imageBasemap),imagesy($imageBasemap),imagesx($imageBasemap),imagesy($imageBasemap));
    //再将二维码图片copy到已经具有底图的真彩色画布中，同样也不会失真
    imagecopymerge($imageCompose,$imageQc, 161,305,0,0,imagesx($imageQc),imagesy($imageQc), 100);
    //将画布保存到指定的jpg文件 保存指定路径
    $lb_qc = '/data/www/api.xxxxxxxxxx.com/stimgas/xxxxxxxxxx'.time().'.jpg';
    imagejpeg($imageCompose,$lb_qc);
    //返回合成图片的路径
    return $lb_qc;
    //imagejpeg($imageCompose);

    }






















}



class Curl {
    private static $_ch;
    private static $_header;
    private static $_body;
    
    private static $_cookie = array();
    private static $_options = array();
    private static $_url = array ();
    private static $_referer = array ();

    /**
     * 调用外部url
     * @param $queryUrl
     * @param $param 参数
     * @param string $method
     * @return bool|mixed
     */
    public static function callWebServer($queryUrl, $param='', $method='get', $is_json=true, $is_urlcode=true) {
        if (empty($queryUrl)) {
            return false;
        }
        $method = strtolower($method);
        $ret = '';
        $param = empty($param) ? array() : $param;
        self::_init();
        if ($method == 'get') {
            $ret = self::_httpGet($queryUrl, $param);
        } elseif($method == 'post') {
            $ret = self::_httpPost($queryUrl, $param, $is_urlcode);
        }
        if(!empty($ret)){
            if($is_json){
                return json_decode($ret, true);
            }else{
                return $ret;
            }
        }
        return true;
    }

    private static function _init() {
        self::$_ch = curl_init();

       // curl_setopt(self::$_ch, CURLOPT_HEADER, 0);
        curl_setopt(self::$_ch, CURLOPT_RETURNTRANSFER, true);
       // curl_setopt(self::$_ch, CURLOPT_IPRESOLVE,CURL_IPRESOLVE_V4);
    //curl_setopt(self::$_ch, CURLOPT_FRESH_CONNECT, true);
    }

    public static function setOption($optArray=array()) {
        foreach($optArray as $opt) {
            curl_setopt(self::$_ch, $opt['key'], $opt['value']);
        } 
    }
    
    private static function _close() {
        if (is_resource(self::$_ch)) {  
            curl_close(self::$_ch);  
        }
        
        return true;
    }
    
    private static function _httpGet($url, $query=array()) {
          
        if (!empty($query)) {  
            $url .= (strpos($url, '?') === false) ? '?' : '&';  
            $url .= is_array($query) ? http_build_query($query) : $query;  
        }  
          
        curl_setopt(self::$_ch, CURLOPT_URL, $url);
        curl_setopt(self::$_ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt(self::$_ch, CURLOPT_HEADER, 0);
        curl_setopt(self::$_ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt(self::$_ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt(self::$_ch, CURLOPT_SSLVERSION, 1);
        //curl_setopt(self::$ch, CURLOPT_HTTPHEADER, array(''Expect: '')); 
    //curl_setopt(self::$ch, CURLOPT_IPRESOLVE, CURL_IPRESOLVE_V4 ); 
        $ret = self::_execute();
        self::_close();
        return $ret;  
    }
    
    private static function _httpPost($url, $query=array(), $is_urlcode=true) {
        if (is_array($query)) {
            foreach ($query as $key => $val) {  
                if($is_urlcode){
                    $encode_key = urlencode($key);
                }else{
                    $encode_key = $key;
                }
                if ($encode_key != $key) {  
                    unset($query[$key]);  
                }
                if($is_urlcode){
                    $query[$encode_key] = urlencode($val);
                }else{
                    $query[$encode_key] = $val;
                }

            }  
        }
        curl_setopt(self::$_ch, CURLOPT_URL, $url);
        curl_setopt(self::$_ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt(self::$_ch, CURLOPT_HEADER, 0);
        curl_setopt(self::$_ch, CURLOPT_POST, true );
        curl_setopt(self::$_ch, CURLOPT_POSTFIELDS, $query);

        curl_setopt(self::$_ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt(self::$_ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        curl_setopt(self::$_ch, CURLOPT_SSLVERSION, 1);


        $ret = self::_execute();
        self::_close();
        return $ret;  
    }
    
    private static function _put($url, $query = array()) {
        curl_setopt(self::$_ch, CURLOPT_CUSTOMREQUEST, 'PUT');  
    
        return self::_httpPost($url, $query);
    }  

    private static function _delete($url, $query = array()) {
        curl_setopt(self::$_ch, CURLOPT_CUSTOMREQUEST, 'DELETE');  
    
        return self::_httpPost($url, $query);
    }  

    private static function _head($url, $query = array()) {
        curl_setopt(self::$_ch, CURLOPT_CUSTOMREQUEST, 'HEAD');
        
        return self::_httpPost($url, $query);
    }  
    
    private static function _execute() {
        $response = curl_exec(self::$_ch);
        $errno = curl_errno(self::$_ch);

        if ($errno > 0) {
            throw new \Exception(curl_error(self::$_ch), $errno);
        }
        return  $response;
    }

    /**
     * 上传文件
     * @param $filename 文件名+路径
     * @return \CURLFile|string 返回可直接用于Curl发送的模式
     * PHP5.5以后，将废弃以@文件名的方式上传文件。
     */
    public static function addFile($filename){
        return class_exists('\CURLFile') ? new \CURLFile($filename) : '@'.$filename;
    }
}











?>